package com.power.using.sharlockchat.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.hjq.toast.ToastUtils;
import com.power.using.sharlockchat.R;
import com.power.using.sharlockchat.adapter.BaseRecyclerAdapter;
import com.power.using.sharlockchat.adapter.SmartViewHolder;
import com.power.using.sharlockchat.base.BaseMainFragment;
import com.power.using.sharlockchat.bean.ShowBean;
import com.power.using.sharlockchat.eventbus.EventCenter;
import com.power.using.sharlockchat.eventbus.StartNewFragmentEvent;
import com.power.using.sharlockchat.utils.SPUtil;
import com.power.using.sharlockchat.view.GridSpacingItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.power.using.sharlockchat.utils.loading.LoadingDialog.cancelLoadingDialog;


/**
 * Created by 聪明一只哈 on 2018/5/25.
 * Time: 2018/5/25  10:35
 */

public class HomeFragment extends BaseMainFragment {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.home_rv)
    RecyclerView homeRv;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    private BaseRecyclerAdapter<ShowBean> mAdapter;
    private MyBroadcastReceiver broadcastReceiver;
    public static final String action = "action.timeUpdate";


    public static HomeFragment newInstance() {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView(view);
        return view;
    }

    private void initView(View view) {
        toolbarTitle.setText("问题列表");

        SPUtil.putString("one_status","1");

        registBroadcast();
    }

    //懒加载
    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);

        initRVData();
        initListener();

    }


    private int i_flag=0;
    private int size_flag=0;
    private Collection<ShowBean> initData() {
        List<ShowBean> list= new ArrayList<>();
        if(size_flag==0){
            size_flag=20;
            i_flag=0;
        }else{
            i_flag=size_flag;
            size_flag+=20;

        }

        for (int i = i_flag; i < size_flag; i++) {
            list.add(new ShowBean("有关数学的问题" + i, "1+1=?","","1"));
        }
        return list;


    }

    /**
     * 加载列表数据
     */
    private void initRVData() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        homeRv.setLayoutManager(layoutManager);
        homeRv.addItemDecoration(new GridSpacingItemDecoration(getResources().getDimensionPixelSize(R.dimen.padding_middle),
                getResources().getDimensionPixelSize(R.dimen.padding_middle), false));

        homeRv.setAdapter(mAdapter = new BaseRecyclerAdapter<ShowBean>(getActivity(),R.layout.item_question_rv) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, ShowBean model, int position) {

                ShowBean showBean = mAdapter.getListShow().get(position);

                holder.text(R.id.tv_item_title,showBean.getTitle());
                holder.text(R.id.tv_item_description, showBean.getDescription());
                holder.image(R.id.image_push,showBean.getDescription());
                holder.textColorId(R.id.tv_item_description, R.color.blue_400);

                String status = showBean.getStatus();
                if("0".equals(status)){
                    holder.text(R.id.tv_ques_status,"已解答");
                }else{
                    holder.text(R.id.tv_ques_status,"未解答");
                }


            }
        });

        //开启自动加载功能（非必须）
        refreshLayout.setEnableAutoLoadMore(true);

        //触发自动刷新
        refreshLayout.autoRefresh();



    }


    private void initListener() {

        homeRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int SCROLL_STATE_IDLE = 0;
            int SCROLL_STATE_TOUCH_SCROLL = 1;
            int SCROLL_STATE_FLING = 2;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == SCROLL_STATE_IDLE) {
                    Log.i("hashiqi", "SCROLL_STATE_IDLE");
                } else if (newState == SCROLL_STATE_TOUCH_SCROLL) {
                    Log.i("hashiqi", "SCROLL_STATE_TOUCH_SCROLL");
                } else if (newState == SCROLL_STATE_FLING) {
                    Log.i("hashiqi", "SCROLL_STATE_FLING");
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        //下拉刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.refresh(initData());
                        refreshLayout.finishRefresh();
                        refreshLayout.setNoMoreData(false);
                    }
                }, 2000);
            }
        });

        //上拉加载
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        if ( mAdapter.getItemCount()>= 40) {
                            Toast.makeText(getActivity(), "数据全部加载完毕", Toast.LENGTH_SHORT).show();
                            refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                        } else {
                            mAdapter.loadMore(initData());
                            refreshLayout.finishLoadMore();
                        }
                    }
                }, 2000);
            }
        });


        //item 点击测试
        mAdapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                ShowBean showBean = mAdapter.getListShow().get(position);
                showBean.setPosition(position);
                if("0".equals(showBean.getStatus())){
                    ToastUtils.show("此问题已经解答");
                    return;
                }
                EventBus.getDefault().post(new StartNewFragmentEvent(ShowQuestionFragment.newInstance(showBean)));

            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i("hashiqiwww", "onResume: ");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i("hashiqiwww", "onStart: ");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("hashiqiwww", "onStop: ");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i("hashiqiwww", "onPause: ");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPost(EventCenter eventCenter){

        if(eventCenter.getEventCode()==1&&mAdapter!=null){

            ShowBean showBean= (ShowBean) eventCenter.getData();
            Log.i("hashiqiwww", "getPost: "+showBean.getPosition());
            mAdapter.notifyItemChanged(showBean.getPosition());
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
        unRegistBroadcast();
        cancelLoadingDialog();
    }

    public void registBroadcast() {
        if (broadcastReceiver == null) {
            broadcastReceiver = new MyBroadcastReceiver();
        }
        IntentFilter filter = new IntentFilter(action);
        getActivity().registerReceiver(broadcastReceiver, filter);
    }

    public void unRegistBroadcast() {
        getActivity().unregisterReceiver(broadcastReceiver);
    }


    public class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //sendBroadcast(new Intent("android.appwidget.action.APPWIDGET_UPDATE"));
            //initNotice();
        }
    }

    private void initNotice() {
        Log.i("broadcastshow", "initNotice: ");
        refreshLayout.autoRefresh(3);
    }
}
